<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Student;
use App\Models\Teacher;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;

class UserController extends Controller
{
    public function index()
    {
        $users = User::with(['student', 'teacher'])->get();
        return response()->json($users);
    }

    public function store(Request $request)
    {
        $request->validate([
            'username' => 'required|string|unique:users',
            'password' => 'required|string|min:6',
            'real_name' => 'required|string',
            'email' => 'required|email|unique:users',
            'role' => ['required', Rule::in(['admin', 'teacher', 'student'])],
            'student_id' => 'required_if:role,student|string|unique:students',
            'class' => 'required_if:role,student|string',
            'major' => 'required_if:role,student|string',
            'teacher_id' => 'required_if:role,teacher|string|unique:teachers',
            'department' => 'required_if:role,teacher|string',
            'title' => 'nullable|string',
        ]);

        $user = User::create([
            'username' => $request->username,
            'password' => Hash::make($request->password),
            'real_name' => $request->real_name,
            'email' => $request->email,
            'role' => $request->role,
        ]);

        if ($request->role === 'student') {
            Student::create([
                'user_id' => $user->id,
                'student_id' => $request->student_id,
                'class' => $request->class,
                'major' => $request->major,
            ]);
        } elseif ($request->role === 'teacher') {
            Teacher::create([
                'user_id' => $user->id,
                'teacher_id' => $request->teacher_id,
                'department' => $request->department,
                'title' => $request->title,
            ]);
        }

        return response()->json($user->load(['student', 'teacher']), 201);
    }

    public function show(User $user)
    {
        return response()->json($user->load(['student', 'teacher']));
    }

    public function update(Request $request, User $user)
    {
        $request->validate([
            'real_name' => 'string',
            'email' => ['email', Rule::unique('users')->ignore($user->id)],
            'password' => 'nullable|string|min:6',
        ]);

        $user->update($request->only(['real_name', 'email']));
        if ($request->has('password')) {
            $user->update(['password' => Hash::make($request->password)]);
        }

        return response()->json($user->load(['student', 'teacher']));
    }

    public function destroy(User $user)
    {
        $user->delete();
        return response()->json(null, 204);
    }
} 